package thread;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class ThreadDemo2 {

    public static void main(String[] args) {
        BlockingQueue<Integer> blockingQueue = new LinkedBlockingQueue<>();

        //创建两个线程来作为生产者和消费者
        Thread customer = new Thread(() ->{ //消费者
            //消费者要做的就是从队列里拿元素
            while (true) {
                try {
                    Integer result = blockingQueue.take();
                    System.out.println("消费元素：" + result);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        customer.start(); //启动

        Thread producer = new Thread(() -> { //生产者
            //生产者的任务是往队列中放元素
            int count = 0; //元素个数
            while (true) {
                try {
                    blockingQueue.put(count);
                    System.out.println("生产元素：" + count);
                    count++;
                    //限制生产的速度
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        producer.start(); //启动
    }
}
